import { login, logout,getMenu } from '@/api/user'
import { getToken, setToken, removeToken ,getUser,setUser,removeUser } from '@/utils/auth'
const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    userInfo: getUser(),
  }
}
const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USER: (state, users) => {
    state.userInfo = users
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
}
/* 设置路由组件 */
function getRouterComponent (routes) {
  routes.forEach(item => {
    if (item.children && item.children.length > 0) {
      getRouterComponent(item.children)
    } else {
      delete item.redirect
      delete item.children
    }
  })
  return routes
}
const actions = {
  // user login
  Login({ commit }, userInfo) {
    const { loginName, password } = userInfo
    return new Promise((resolve, reject) => {
      login(userInfo).then(response => {
        const data = response.object
        commit('SET_USER', data.userInfo)
        commit('SET_TOKEN', data.token)
        setUser(data.userInfo)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // user logout
  logout({ commit, state }) {
    return new Promise(resolve => {
      removeToken()
      removeUser()
      commit('RESET_STATE')
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

